var fs = require('fs');
var _ = require('lodash');


var projectJson = {};

readProjectJson();

////////////////////////////////

function readProjectJson() {
  fs.readFile('project.json', 'utf8', function(err, data) {
    projectJson = JSON.parse(data);
    createProjectCatalogs(projectJson.catalog);
  });
}

function createProjectCatalogs(catalog, path) {
  path = path || '';
  _.forEach(catalog, function(value, key) {
    if (_.isArray(value)) {
      _.forEach(value, function(fileName) {
        createFile(path, fileName, key, value)
      })
    } else if (_.isObject(value)) {
      fs.stat(path + key, function(err, stats) {
        if (!stats) {
          fs.mkdir(path + key, function() {
            console.log('创建文件夹：' + path + key);
            createProjectCatalogs(value, path + key + '/');
          })
        } else {
          createProjectCatalogs(value, path + key + '/');
        }
      })
    } else {
      createFile(path, value, key, value)
    }
  })
}

function createFile(filePath, fileName, postfix, fileNameArr) {
  fs.stat(filePath + fileName + postfix, function(err, stats) {
    if (!stats) {
      var pathArr = filePath.split('/');
      pathArr.pop();
      var fileContent = copyTemplateFile(pathArr, postfix);
      pathArr = filePath.split('/');
      pathArr.pop();
      fs.writeFileSync(filePath + fileName + postfix, handleContent(fileContent, fileName, pathArr));
      console.log('创建文件：' + filePath + fileName + postfix);
    }
  })
}

function copyTemplateFile(pathArr, postfix) {
  var content = '';

  var temFilePath = projectJson['template'] + _.join(pathArr, '.') + postfix;
  try {
    fs.statSync(temFilePath);
    content = fs.readFileSync(temFilePath, 'utf8');
    console.log('从模板文件[' + temFilePath + ']读取内容');
  } catch (err) {
    if (pathArr.length > 0) {
      pathArr.pop();
      content = copyTemplateFile(pathArr, postfix);
    }
  }

  return content;
}

function handleContent(content, fileName, pathArr) {

  var compiled = _.template(content);

  content = compiled({
    'projectJson': projectJson,
    'fileName': fileName,
    'pathArr': pathArr,
    'current_date': new Date(),
  });

  return content
}